/**
 * sidebar
 * 结构:
 * <div id=''>
 * 		<div class="sidebar-btn"></div>
 * 		<div class="sidebar-content"></div>
 * </div>
 * @param
 * options = {
 * 		direction: 'right',
 * 		duration: 600,
 * 		onclose: fn,
 * 		onopen: fn
 * }
 * @author  tanggf
 */
(function($){
	$.fn.sidebar = function(options){
		options = $.extend({
			direction: 'right',
			duration: 500,
			closeBtnClass: 'btn_hc',
			openBtnClass: 'btn_ho',
			onclose: function(){},
			onopen: function(){},
			firstopen: function(){}						
		}, options);
		
		return this.each(function(){
			_get_sidebar(this, options);
		});
	};
	
	function _get_sidebar(ele, options){
		var $this = $(ele);
		var sb = $this.data("_wt_sidebar_");
		if( ! sb){
			sb = new _Sidebar(ele, options);
			$this.data("_wt_sidebar_", sb);
		}
		return sb;
	}
	
	function _Sidebar(ele, options){
		this.$ele = $(ele);
		this.options = options;
		this._init();
	}
	
	_Sidebar.prototype = {
		_init: function(){
			this.$btn = this.$ele.children("div.sidebar-btn");
			this.$content = this.$ele.children("div.sidebar-content");
			this.$close = this.$ele.find("a.sidebar-close");
			this.width = this.$content.innerWidth();	
			this.firstopen = true;
			this.open = false;
			this.sliding = false;
			
			var self = this;
			this.$btn.click(function(){
				if(self.open){
					self._slide_to_close();
				}else{
					self._slide_to_open();
				}							
			}).delayhover(400, function(){
				if( ! self.open){
					self._slide_to_open();
				}
			});
			
			this.$close.click(function(){
				if(self.open){
					self._slide_to_close();
				}				
				return false;
			});
			
			this.$ele.mouseleave(function(){
				if(self.open){
					self._slide_to_close();		
				}								
			});
		},
		
		_slide_to_close: function(){
			this.__slide__("close");		
		},
		
		_slide_to_open: function(){
			this.__slide__("open");			
		}, 
		
		__slide__: function(action){	
			if(this.sliding){
				return;
			}else{
				this.sliding = true;
			}
			if(action == 'open' && this.firstopen){
				this.firstopen = false;
				this.options.firstopen();
			}
			
			var width = (action == 'close')? -this.width : 0;			
			var css;
			if(this.options.direction == 'right'){				
				css = {'right': width};
			}else{
				css = {'left': width};
			}
			
			var self = this;
			this.$ele.animate(css, this.options.duration,  function(){					
				if(action == 'close'){
					self.options.onclose();
					self.open = false;
					self.$btn.removeClass(self.options.openBtnClass).addClass(self.options.closeBtnClass);
				}else{
					self.options.onopen();
					self.open = true;
					self.$btn.removeClass(self.options.closeBtnClass).addClass(self.options.openBtnClass);
				}
				self.sliding = false;
			});
		}
	};
})(jQuery);